<?php
/**
 * Receipt
 *
 * Обработка данных поступления товаров
 *
 * @author Mike
 */
class Receipt extends ActiveRecord {
	protected $tableName = 'product_receipt';
	public $pkName = 'ID_product_receipt';
	
	protected $arrSettings = array('created_at' => true, 'author' => true, 'updated_at' => true);

	public $validatesLengthOf = array(
			'comment' => array('min' => 2, 'max' => 1024, 'message' => 'Описание - 2-1024 символов', 'allowNull' => true)
	);
	
	public $validatesFormatOf = array(
			'count' => array('with' => '#^[0-9]{1,2}$#ui', 'message' => 'Количество заполнено неверно'),
			'our_price' => array('with' => '#^[0-9]{1,5}$#ui', 'message' => 'Наша цена заполнена неверно')
	);
	
	public function beforeValidation() {
		$objDB = Service_Database::instanse();
		if(!$this->tableFields['ID_product'] || !$this->tableFields['ID_size']) $this->errorValidated('', 'Переданы не все параметры');
		
		$objSize = new Size($this->tableFields['ID_size']);
		if(!$objSize->id) $this->errorValidated('', 'Передан несуществующий размер');
		
		$objProduct = new Product($this->tableFields['ID_product']);
		if(!$objProduct->id) $this->errorValidated('', 'Передан несуществующий размер');
		
		if($objSize->getField('type') != $objProduct->getField('type')) $this->errorValidated('', 'Несоответствие типов размеров');
	}
	
	public function afterCreate() {
		$objDB = Service_Database::instanse();
		$time = gmdate("Y-m-d H:i:s", time());
		$stmt = "SELECT *
				FROM `product_active` 
				WHERE `product_active`.`ID_size`='" . $this->getField('ID_size') . "' AND `product_active`.`ID_product`='" . $this->getField('ID_product') . "'";
		
		if($objDB->selectOneValue($stmt)) {
			$stmt = "UPDATE `product_active` 
					SET `product_active`.`count` = `product_active`.`count` + " . $this->getField('count') . ", `product_active`.`updated_at` = '" . $time . "' 
					WHERE `product_active`.`ID_product`='" . $this->getField('ID_product') . "' AND `product_active`.`ID_size`='" . $this->getField('ID_size') . "'"; 
		}
		else {
			$stmt = "INSERT INTO `product_active`(`ID_product`, `ID_size`, `count`, `created_at`) 
					VALUES('" . $this->getField('ID_product') . "', '" . $this->getField('ID_size') . "', '" . $this->getField('count') . "', '" . $time . "')";
		}
		$objDB->query($stmt);
	}
}